Imports Odm.Data.Common

'ODM Tools
'Copyright (c) 2007, Utah State University
'All rights reserved.
'Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
'*           Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
'*           Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
'*           Neither the name of the Utah State University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Public Class frmCreateNewVariable

#Region "Member Variables"
    Dim m_variable As Odm.Data.Model.Variable
    Dim m_deriveMethod As String
    Dim m_Loading As Boolean
#End Region

#Region "Form Control Functions"

    Public Sub New(ByRef variable As Odm.Data.Model.Variable, ByVal deriveMethod As String)
        'Inputs:  variable -> variable to be used as based variable to create a new one
        'Outputs: None
        MyBase.New()
        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        m_deriveMethod = deriveMethod

        variable.ID = -1
        variable.Code = String.Empty

        m_variable = variable

        '2. set that loading the form
        m_Loading = True
    End Sub

    Private Sub frmCreateNewVariable_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Loads and Initializes the frmCreateNewVariable form when it is shown
        'the inputs/outputs are standard for form events
        Try
            '1. Load ReadOnly Info
            LoadReadOnly()
            '2. Load Selectable Info
            'Variable Code
            tboxVarCode.Text = String.Empty
            'Variable Names
            LoadVarNames()
            'Variable Units
            LoadVarUnits()
            'Speciation
            LoadSpeciation()

            '3. Enable/Disable Create button
            If HaveValidSelParameters() Then
                'enable create btn
                btnCreateVariable.Enabled = True
            Else
                btnCreateVariable.Enabled = False
            End If

            '5. Set that done loading the form
            m_Loading = False
        Catch ex As Exception
            ShowError("An Error occurred while loading the form to Derive a Data Series." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

    Private Sub btnCreateVariable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateVariable.Click
        Try
            'create the new variable in the database
            If Not (CreateNewVariable()) Then
                'don't close, allow user to try again
                Exit Try
            Else
                'variable successfully created, close form = OK
                Me.DialogResult = Windows.Forms.DialogResult.OK
                'close the form
                Me.Close()
            End If
        Catch ex As Exception
            ShowError("An Error occurred while creating the new Variable in the Database." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        'Handles the Cancel Button click, closes the form
        'the inputs/outputs are standard for form events

        'set that clicked cancel
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
        'close the form
        Me.Close()
    End Sub

#End Region

#Region "Data Selection Functionality"

    Private Sub tboxVarCode_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tboxVarCode.KeyPress
        'see if enter key = pressed, if so, validate
        Select Case e.KeyChar
            Case vbCr, vbCrLf, vbLf
                tboxVarCode_Validating(sender, New System.ComponentModel.CancelEventArgs())
        End Select
    End Sub

    Private Sub tboxVarCode_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles tboxVarCode.Validating
        Try
            If Not (m_Loading) Then
                '1. see if have a value
                If tboxVarCode.Text <> "" Then
                    '2. see if it exists in the database already
                    'get the variable code
                    'check the database for the specified variable code
                    Dim variable As Odm.Data.Model.Variable = g_CurrDataSource.GetVariable(tboxVarCode.Text)

                    If Not (variable Is Nothing) Then
                        'there was a value returned from the database -> this code already exists
                        MsgBox("The Variable Code that you entered already exists in the database.  Duplicate Codes cannot exist in the database!!  Please specify a different Variable Code.", MsgBoxStyle.Exclamation)
                        'disable create btn
                        btnCreateVariable.Enabled = False
                        'exit
                        Exit Try
                    End If

                    'check to see other parameters = good, if so, enable create btn
                    If HaveValidSelParameters() Then
                        btnCreateVariable.Enabled = True
                    Else
                        btnCreateVariable.Enabled = False
                    End If
                Else
                    'disable create btn
                    btnCreateVariable.Enabled = False
                End If
            End If
        Catch ex As Exception
            ShowError("An Error occurred while validating the Variable Code specified." & vbCrLf & "Message = " & ex.Message, ex)
            'disable create btn
            btnCreateVariable.Enabled = False
        End Try
    End Sub

    Private Sub cboxVarName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboxVarName.SelectedIndexChanged
        Try
            If Not (m_Loading) Then
                '1. see if selected index is valid
                If cboxVarName.SelectedIndex >= 0 Then
                    'check to see other parameters = good, if so, enable create btn
                    If HaveValidSelParameters() Then
                        btnCreateVariable.Enabled = True
                    Else
                        btnCreateVariable.Enabled = False
                    End If
                Else
                    'disable create btn
                    btnCreateVariable.Enabled = False
                End If
            End If
        Catch ex As Exception
            ShowError("An Error occurred when a new Variable Name was selected." & vbCrLf & "Message = " & ex.Message, ex)
            'disable create btn
            btnCreateVariable.Enabled = False
        End Try
    End Sub

    Private Sub cboxVarUnits_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboxVarUnits.SelectedIndexChanged
        Try
            If Not (m_Loading) Then
                '1. see if selected index is valid
                If cboxVarUnits.SelectedIndex >= 0 Then
                    'check to see other parameters = good, if so, enable create btn
                    If HaveValidSelParameters() Then
                        btnCreateVariable.Enabled = True
                    Else
                        btnCreateVariable.Enabled = False
                    End If
                Else
                    'disable create btn
                    btnCreateVariable.Enabled = False
                End If
            End If
        Catch ex As Exception
            ShowError("An Error occurred when new Variable Units were selected." & vbCrLf & "Message = " & ex.Message, ex)
            'disable create btn
            btnCreateVariable.Enabled = False
        End Try
    End Sub

    Private Sub cboxSpeciation_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboxSpeciation.SelectedIndexChanged
        Try
            If Not (m_Loading) Then
                '1. see if selected index is valid
                If cboxSpeciation.SelectedIndex >= 0 Then
                    'check to see other parameters = good, if so, enable create btn
                    If HaveValidSelParameters() Then
                        btnCreateVariable.Enabled = True
                    Else
                        btnCreateVariable.Enabled = False
                    End If
                Else
                    'disable create btn
                    btnCreateVariable.Enabled = False
                End If
            End If
        Catch ex As Exception
            ShowError("An Error occurred when a new Speciation was selected." & vbCrLf & "Message = " & ex.Message, ex)
            'disable create btn
            btnCreateVariable.Enabled = False
        End Try
    End Sub

#End Region

#Region "Loading Functions"

    Private Sub LoadReadOnly()
        Try
            '1.load the previously defined parameters for the variable
            'Time Support
            tboxTSValue.Text = m_variable.TimeSupport.Value
            tboxTSUnits.Text = m_variable.TimeSupport.Name
            'Value Type
            tboxValueType.Text = m_variable.ValueType
            'Data Type
            tboxDataType.Text = m_variable.DataType
            'General Category
            tboxGeneralCategory.Text = m_variable.GeneralCategory
            'Sample Medium
            tboxSampleMedium.Text = m_variable.SampleMedium
            'No Data Value
            tboxNoDataValue.Text = m_variable.NoDataValue
            'IsRegular
            tboxIsRegular.Text = m_variable.IsRegular.ToString
        Catch ex As Exception
            ShowError("An Error occurred while loading the Defined Parameters for the Variable to create." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

    Private Sub LoadVarNames()
        Try
            '1. clear out any old data
            cboxVarName.Items.Clear()
            cboxVarName.Text = ""

            '2. Load Variable names based on m_DeriveMethod
            Select Case m_deriveMethod
                Case g_DeriveMethod_Smooth, g_DeriveMethod_Aggregate
                    'load only the given variable name
                    cboxVarName.Items.Add(m_variable.Name)
                    'select this value
                    cboxVarName.SelectedIndex = 0
                Case g_DeriveMethod_Algebraic
                    'load all variable names from the database
                    cboxVarName.DisplayMember = "Name"
                    cboxVarName.DataSource = g_CurrDataSource.GetTerms(TermType.VariableName).ToList()
                    cboxVarName.Text = ""
            End Select

        Catch ex As Exception
            ShowError("An Error occurred while loading the available Variable Names from the database." & vbCrLf & "Message = " & ex.Message, ex)
            'release Resources
        End Try
    End Sub

    Private Sub LoadVarUnits()
        Try
            '1. clear out any old data
            cboxVarUnits.Items.Clear()
            cboxVarUnits.Text = ""

            '2. Load Variable names based on m_DeriveMethod
            Select Case m_deriveMethod
                Case g_DeriveMethod_Smooth, g_DeriveMethod_Aggregate
                    'load only the given variable name
                    cboxVarUnits.DisplayMember = "Name"
                    cboxVarUnits.Items.Add(m_variable.Unit)
                    'select this value
                    cboxVarUnits.SelectedIndex = 0
                Case g_DeriveMethod_Algebraic
                    'load all variable units from the database
                    cboxVarUnits.DisplayMember = "Name"
                    cboxVarUnits.DataSource = g_CurrDataSource.GetUnits.ToList()

            End Select
        Catch ex As Exception
            ShowError("An Error occurred while loading the available Variable Units from the database." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

    Private Sub LoadSpeciation()
        'This function loads the Selectable Variable Speciation from the Database
        'Inputs:  None
        'Outputs: None
        Try
            '1. clear out any old data
            cboxSpeciation.Items.Clear()
            cboxSpeciation.Text = ""

            '2. Load Variable names based on m_DeriveMethod
            Select Case m_deriveMethod
                Case g_DeriveMethod_Smooth, g_DeriveMethod_Aggregate
                    'load only the given variable name
                    cboxSpeciation.Items.Add(m_variable.Speciation)
                    'select this value
                    cboxSpeciation.SelectedIndex = 0
                Case g_DeriveMethod_Algebraic
                    'load all variable names from the database
                    cboxSpeciation.DisplayMember = "Name"
                    cboxSpeciation.DataSource = g_CurrDataSource.GetTerms(TermType.Speciation).ToList()
            End Select

        Catch ex As Exception
            ShowError("An Error occurred while loading the available Speciation values from the database." & vbCrLf & "Message = " & ex.Message, ex)
        End Try
    End Sub

#End Region

#Region "Validation Functions"

    Private Function HaveValidSelParameters() As Boolean
        'this function return whether or not all of the selectable parameters are valid or not
        'Inputs:  None
        'Outputs: Boolean -> returns if selectable parameters are valid or not
        If String.IsNullOrEmpty(tboxVarCode.Text) Then
            Return False
        ElseIf String.IsNullOrEmpty(cboxVarName.Text) Then
            Return False
        ElseIf String.IsNullOrEmpty(cboxVarUnits.Text) Then
            Return False
        ElseIf String.IsNullOrEmpty(cboxSpeciation.Text) Then
            Return False
        Else
            Return True
        End If
    End Function

#End Region

#Region "Updating Functions"

    Private Function CreateNewVariable() As Boolean
        Try
            m_variable.Code = tboxVarCode.Text
            m_variable.Name = cboxVarName.Text
            m_variable.Unit = cboxVarUnits.SelectedItem
            m_variable.Speciation = cboxSpeciation.Text

            g_CurrDataSource.CreateVariable(m_variable)

            Return True
        Catch ex As Exception
            ShowError("An Error occurred while creating the new Variable in the Database." & vbCrLf & "Message = " & ex.Message)
        End Try
        Return False
    End Function

#End Region

End Class